package com.mindata.blockmanager.manager;

import cn.hutool.core.bean.BeanUtil;
import com.mindata.blockmanager.bean.GridResultDto;
import com.mindata.blockmanager.bean.PermissionData;
import com.mindata.blockmanager.bean.PermissionVo;
import com.mindata.blockmanager.bean.QueryPage;
import com.mindata.blockmanager.constant.PermissionType;
import com.mindata.blockmanager.model.Member;
import com.mindata.blockmanager.model.MemberGroup;
import com.mindata.blockmanager.model.Permission;
import com.mindata.blockmanager.repository.MemberGroupRepository;
import com.mindata.blockmanager.repository.PermissionRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wuweifeng wrote on 2018/4/10.
 */
@Service
public class PermissionManager {
    @Resource
    private PermissionRepository permissionRepository;
    @Resource
    private MemberManager memberManager;
    @Resource
    private MemberGroupRepository memberGroupRepository;

    /**
     * 查询某个联盟内的所有权限
     *
     * @param memberName memberName
     * @return PermissionData
     */
    public PermissionData findGroupPermission(String memberName) {
        PermissionData permissionData = new PermissionData();
        int groupId = memberManager.findGroupId(memberName);
        permissionData.setPermissions(findPermission(groupId));
        permissionData.setCode(String.valueOf(0));
        return permissionData;
    }

    private List<Permission> findPermission(int groupId) {
        return permissionRepository.findByGroupId(groupId);
    }

    public void save(Permission permission) {
        permissionRepository.save(permission);
    }

    public void del(long id) {
        permissionRepository.delete(id);
    }

    public PermissionVo findById(long id) {
        PermissionVo vo = null;
        Permission member = permissionRepository.getOne(id);
        if (member != null) {
            vo = new PermissionVo();
            BeanUtil.copyProperties(member, vo);
        }
        return vo;
    }

    public void updatePermission(Permission permission) {
        permissionRepository.save(permission);
    }

    public GridResultDto<PermissionVo> pageQuery(QueryPage page) {
        if ("groupName".equals(page.getSort())) {
            page.setSort("groupId");
        }
        Sort sort = new Sort(page.getOrder(), page.getSort());    //排序
        Pageable pageable = new PageRequest(page.getPage(), page.getRows(), sort);

        //封装条件查询对象Specification
        // Root 用于获取属性字段，CriteriaQuery可以用于简单条件查询，CriteriaBuilder 用于构造复杂条件查询
        Specification<Permission> specification = (root, query, cb) -> {
            //集合 用于封装查询条件
            List<Predicate> list = new ArrayList<>();
            //简单单表查询
            if (StringUtils.isNotBlank(page.getGroupId())) {
                list.add(cb.equal(root.get("groupId").as(String.class), page.getGroupId()));
            }
            if (StringUtils.isNotBlank(page.getPubKey())) {
                list.add(cb.like(root.get("publicKey").as(String.class), "%" + page.getPubKey() + "%"));
            }
            return cb.and(list.toArray(new Predicate[0]));
        };
        //调用业务层，返回Page
        Page<Permission> pageData = permissionRepository.findAll(specification, pageable);

        //将返回page对象转换为datagrid所需要的数据格式
        List<PermissionVo> vos = new ArrayList<>();
        pageData.getContent().forEach(e -> {
            PermissionVo vo = new PermissionVo();
            BeanUtil.copyProperties(e, vo);
            vo.setPermissionTypeDesc(PermissionType.fromValue(e.getPermissionType()).getValue());
            MemberGroup memberGroup = memberGroupRepository.findByGroupId(e.getGroupId());
            if (memberGroup != null) {
                vo.setGroupName(memberGroup.getName());
            }
            vos.add(vo);
        });
        return GridResultDto.createGridResultDto(vos, pageData.getTotalElements());
    }

    public Permission findFirstByGroupId(int groupId) {
        return permissionRepository.findFirstByGroupId(groupId);
    }
}
